package com.gjy.jjwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-01-22 10:26:09
 */
public class JwtUtil {

    private final String secretKey = "your_secret_key";
    private final long accessTokenValidity = 15 * 60 * 1000; // 15分钟
    private final long refreshTokenValidity = 7 * 24 * 60 * 60 * 1000; // 7天

    public String generateAccessToken(String username) {
        return generateToken(username, accessTokenValidity);
    }

    public String generateRefreshToken(String username) {
        return generateToken(username, refreshTokenValidity);
    }

    private String generateToken(String username, long validity) {
        long now = System.currentTimeMillis();
        Date expiryDate = new Date(now + validity);
        JwtBuilder builder = Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date(now))
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512, secretKey);
        return builder.compact();
    }

    public Claims validateToken(String token) {
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(token)
                .getBody();
    }

}
